
//  StatusListViewModel.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/11.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import Foundation
import SDWebImage

class StatusListViewModel{

    //定义一个属性
   lazy var statusList = [StatusViewModel]()
    
    /// 下拉刷新计数
    var pulldownCount: Int?
    
/// 加载网络数据
    func loadStatus(isPullup isPullup: Bool,finished: (isSuccessed: Bool)->()) {
    
        // 下拉刷新 - 数组中第一条微博的id
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        
        //上拉刷新  数组的最后一条微博id
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
        //加载数据
        StatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            
            guard let array = array else {
            
                finished(isSuccessed: false)
                
                return
            }
            
        
        
            //字典转模型
            var dataList = [StatusViewModel]()
            
            for dict in array {
                
                dataList.append(StatusViewModel(status: Status(dict: dict)))
            }
            
            //记录下拉刷新的数据
            self.pulldownCount = (since_id > 0) ? dataList.count : nil
            
            
            if max_id > 0 {
            
                self.statusList += dataList
                
            }else{
            
                self.statusList = dataList + self.statusList
            }
            
            //缓存单张图片
            self.cacheSingleImage(dataList,finished: finished)
            
//            finished(isSuccessed: true)
        
        }
    
    }


    //缓存单张图片
    private func cacheSingleImage(dataList: [StatusViewModel],finished: (isSuccessed: Bool)->()) {
    
        //1.创建一个调度组
        let group = dispatch_group_create()
        
        //缓存数据的长度
        var dataLength = 0
        
        //2.遍历视图模型数组
        for vm in dataList {
        
            //判断是否为单张图片
            if vm.thumbnailUrls?.count != 1 {
            
                continue
                
            }
            
            //获取URL
            let url = vm.thumbnailUrls?.first
            print("开始缓存图片\(url)")
            
                //利用SDwebImage进行单张缓存下载

            //进组
            dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(
                url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                
                    //单张图片下载完成计算长度
                if let img = image,
                    let data = UIImagePNGRepresentation(img){
                
                        //累加数据
                        dataLength += data.length
                
                }
                
                //出组
                dispatch_group_leave(group)
                
            })
        }
    
        //3.监听调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("缓存完成\(dataLength / 1024)K")
            
            finished(isSuccessed: true)
        }
    
    }
    
    
}
    
